<?php
declare (strict_types = 1);

namespace app\model;


use app\exception\ModelEmptyException;
use app\exception\ModelException;

class SubContent extends Model
{

    public function category(): \think\model\relation\BelongsToMany
    {
        return $this->belongsToMany(Category::class,'category_sub_content','category_id','sub_content_id');
    }

    public function tag(): \think\model\relation\BelongsToMany
    {
        return $this->belongsToMany(Tag::class,'tag_sub_content');
    }

    public function thumbnail(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(Attachment::class,'thumbnail','id');
    }

    public function cover(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(Attachment::class,'cover','id');
    }

    /**
     * @throws ModelException
     */
    public function updateSubContent($where, $param): array
    {
        try{
            $res =  self::where($where)->update($param);
        }catch(\Exception $e){
            throw new ModelException($e->getMessage());
        }
        return dataReturn($this->sucCode,$this->updateMsg,$res);
    }

    /**
     * @throws ModelException
     * @throws ModelEmptyException
     */
    public function getSubContent($where,$with=[]): array
    {
        try{
            $res =  self::with($with)->where($where)->find();
            if(empty($res)) {
                throw new ModelEmptyException();
            }
        }catch (ModelEmptyException $me){
            throw new ModelEmptyException('内容不存在');
        }
        catch(\Exception $e){
            throw new ModelException($e->getMessage());
        }
        return dataReturn($this->sucCode,$this->getMsg,$res);
    }

    public function getCoverAttr($value)
    {
        if(empty($value)){
            return null;
        }
        return $value;
    }

    public function getThumbnailAttr($value)
    {
        if(empty($value)){
            return null;
        }
        return $value;
    }

}
